/*  
  -- The Lime II Project -- 

  A tuplespaces-based middleware for coordinating agents and mobile hosts.
  Copyright (C) 2005.
  Gian Pietro Picco, Amy L. Murphy, Lorenzo Bellini.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received this copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 */

package sagroup.dracots.testing;

import lime2.Location;
import sagroup.dracots.DracoTS;
import sagroup.dracots.DracoTuple;
import sagroup.dracots.ShareTuple;
import sagroup.dracots.commands.AddReplicaRequestByEntryCommand;
import sagroup.dracots.TupleType;

/**
 * A simple agent performing some basic operation.<br>
 * 
 * @author Huang Xiaodong
 */

public class AddReplica implements Runnable {
	/**
	 * Constructor method (default). Destination location is here.
	 */
	public AddReplica() {
	}

	/**
	 * Run method.
	 */
	public void run() {
		System.out.println("AddReplica Agent started");
		try {
			DracoTS dts = DracoTS.get("testing");
			ShareTuple template = ShareTuple.createTypeTemplate(new TupleType(
					"type3"));
			DracoTuple[] sts = dts.rdg(template);
			System.out.println("Read tuples of type3");
			if (sts != null) {
				AddReplicaRequestByEntryCommand.ReplicaRequestEntry[] entries = 
					new AddReplicaRequestByEntryCommand.ReplicaRequestEntry[sts.length];
				for (int i = 0; i < sts.length; ++i) {
					dts.out(((ShareTuple) sts[i]).replicate(Location.HERE));
					entries[i] = new AddReplicaRequestByEntryCommand.ReplicaRequestEntry(
							((ShareTuple) sts[i]).getVID(),
							((ShareTuple) sts[i]).getVer());
				}
				dts.addReplica(sts[0].getCurr(), entries);
				System.out.println("Dest of AddReplicaRequest is "
						+ sts[0].getCurr());
				System.out.println("Entries are " + entries);
				System.out.println("Replications added.");
			}
			System.out.println("Agent done!");
		} catch (Exception e) {
			System.out.println("Operation failed!");
			e.printStackTrace();
		}
	}
}